﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using WinSwitchNew;

namespace Produce
{
    class Program
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public readonly IntPtr HFILE_ERROR = new IntPtr(-1);


        private byte byteConvert(byte b)
        {
            return (byte)(b - 128);
            //return (byte)(~b);
        }

        string suffix = "exe" ;
        private void PackDir( string path )
        {
            DirectoryInfo dir = new DirectoryInfo( path ) ;

            DirectoryInfo[] subdirs = dir.GetDirectories() ;

            //递归子文件夹
            if ( subdirs.Length > 0 )
            {
                foreach (DirectoryInfo cfc in subdirs)
                {
                    
                    Console.WriteLine("pack directory2:" + cfc.ToString());
                    PackDir(path + "\\" + cfc.Name );
                    
                }
            }
            //递归写文件
            FileInfo[] finfo = dir.GetFiles();
            foreach ( FileInfo info in finfo )
            {
                IntPtr vHandle = _lopen(info.FullName, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (vHandle == HFILE_ERROR)
                {
                    //MessageBox.Show("文件被占用！");
                    Console.WriteLine(info.FullName + "文件被占用！");
                    CloseHandle(vHandle);     //判断之后一定要关闭！！！
                    continue;
                }
                CloseHandle(vHandle);     //判断之后一定要关闭！！！

                ConvertFile(info.FullName);

            }
        }

        /// <summary>
        /// 顶部文件夹特殊处理，目标，不记录打包位置更上级的目录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="Fs"></param>
        private void PackTopDir(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);

            DirectoryInfo[] subdirs = dir.GetDirectories();
            //递归子文件夹
            if (subdirs.Length > 0)
            {
                foreach (DirectoryInfo cfc in subdirs)
                {
                    
                    Console.WriteLine("pack directory1:" + cfc.ToString());
                    PackDir(path + "\\" + cfc.Name);
                    
                }
            }
            //递归写文件
            FileInfo[] finfo = dir.GetFiles();
            foreach (FileInfo info in finfo)
            {
                IntPtr vHandle = _lopen(info.FullName, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (vHandle == HFILE_ERROR)
                {
                    Console.WriteLine(info.FullName + "文件被占用！");
                    CloseHandle(vHandle);     //判断之后一定要关闭 
                    continue;
                }
                CloseHandle(vHandle);     //判断之后一定要关闭 

                ConvertFile(info.FullName);
            }


        }

        /// <summary>
        /// 获得该路径的上一级路径
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        string GetUpLevelPath(String raw)
        {
            int index = raw.LastIndexOf('\\');

            if (index == -1)
                return raw;
            else
                return raw.Substring(0, index);
        }


        void Pack(string SelectedPath )
        {
            //string SelectedPath = Environment.CurrentDirectory + "\\";
            {


                PackTopDir(SelectedPath );




                Console.WriteLine("生成完毕！");
            }

        }

        static void ConvertFile(string filePath )
        {
            // string filePath = @"C:\path\to\your\file.txt"; // 替换为你的文件路径

            try
            {
                //判断后缀，如果是ui则不转 qrc
                if (filePath.EndsWith(".ui") || filePath.EndsWith(".qrc")) {
                    return;
                }

                // 1. 读取文件内容（自动检测编码）
                string originalContent = File.ReadAllText(filePath, Encoding.UTF8 );

                // 2. 将内容转换为ANSI编码（Windows-1252）
                //byte[] ansiBytes = Encoding.GetEncoding(1252).GetBytes(originalContent);
                byte[] ansiBytes = Encoding.Default.GetBytes(originalContent);

                // 3. 将转换后的内容写回原文件
                File.WriteAllBytes(filePath, ansiBytes);

                Console.WriteLine("文件已成功转换为ANSI编码并保存。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }

        static void Main(string[] args)
        {
            Program program = new Program();

            program.Pack(args[0]);

            Console.ReadKey();
        }
    }
}
